import React, { useState, useEffect } from 'react'
import { Button,  Row, Col, Form, Input, Select, message, Image, Spin} from 'antd'
import { storage } from '@/utils/utils'
import { email, telephone } from '@/utils/regexp'
import Link from 'next/link'
import { RightOutlined } from '@ant-design/icons'
import styles from '@/styles/updateInfo.module.scss'
import SelectCity from '@/components/select-city'
import Header from '@/components/header/header'
import UploadFile from '@/components/upload-img'
import userInfoModel from 'pages/model/user-info/index.js'
import { useRouter } from 'next/router'
const { Option } = Select
const { TextArea } = Input

function UpdateInfo () {
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  // 头像
  const [avatarFile, setAvatarFile] = useState([])
  // 封面
  const [coverFile, setCoverFile] = useState([])
  const [address, setAddress] = useState([])
  const [form] = Form.useForm()
  // 提交表单
  const submitForm = () => {
    form.validateFields().then(values => {
      if (!telephone.test(values.iphone)) {
        message.error('手机号格式错误')
        return
      }
      if (!email.test(values.email)) {
        message.error('邮箱格式错误')
        return
      }
      userInfoModel.updateUserInfo({
        data: {
          id: JSON.parse(storage.get('next_blog_userInfo'))?.id,
          username: values.username,
          job: values.job,
          iphone: values.iphone,
          email: values.email,
          provinceCityDistrict: address,
          avatar: avatarFile[0].url,
          gender: values.gender,
          addressDetail: values.details_address,
          coverUrl: coverFile[0].url
        }
      }).then(data => {
        if (data.success) {
          message.success('修改成功')
          storage.set('next_blog_userInfo', JSON.stringify(data.datas))
          router.push('/my-info')
        }
      })
    })
  }
  useEffect(() => {
    setLoading(true)
    userInfoModel.getUserInfoDeatil({
      data: {
        id: JSON.parse(storage.get('next_blog_userInfo'))?.id
      }
    }).then(({datas}) => {
      if (datas) {
        form.setFieldsValue({
          username: datas.username,
          iphone: datas.iphone,
          email: datas.email,
          gender: datas.gender === '女' ? 0 : 1,
          job: datas.job,
          details_address: datas.detailAddress,
          avatarFile: [
            {
              name: `${datas.username}的头像`,
              url: datas.avatar
            }
          ],
          coverFile: [
            {
              name: `${datas.username}的封面`,
              url: datas.coverUrl
            }
          ],
        })
        setAvatarFile([
          {
            name: `${datas.username}的头像`,
            url: datas.avatar
          }
        ])
        setCoverFile([
          {
            name: `${datas.username}的封面`,
            url: datas.coverUrl
          }
        ])
        setAddress([datas.province, datas.city, datas.area])
        setLoading(false)
      }
    })
  }, [])
  useEffect(() => {
    form.setFieldsValue({
      address
    })
  }, [address, form])
  // 处理输入框禁止输入空格
  const handleSpaces = (e, type) => {
    form.setFieldsValue({
      [type]: e.target.value.replace(/\s+/gu, '')
    })
  }
  return (
    <div className={styles.page} id="info">
      <Header />
      <Spin spinning={loading}>
        <Row justify="center" style={{marginTop: 25}}>
          <Col span={16}>
            <div className={styles.info_box} id="infoBox" >
              <Image preview={false} style={{objectFit: 'cover'}} width="100%" height={240} src={coverFile[0]?.url ? coverFile[0].url : 'http://leyi-blog.oss-cn-shanghai.aliyuncs.com/image/20220227/a650524a72d9282b9df6fcecae1b3d20.jpg'}></Image>
              <div style={{position: 'absolute', top: 200, left: 25, width: 160, height: 160}}>
                <Image width={160} preview={false} height={160} style={{border: '4px solid #fff', borderRadius: 10}} src={avatarFile[0]?.url ? avatarFile[0].url : 'http://leyi-blog.oss-cn-shanghai.aliyuncs.com/image/20220227/75bdb9747d683e881b78953d37f816d7.jpg'}> </Image>
              </div>
              <div className={styles.back}>
                <Link prefetch href={{pathname: '/my-info'}}><span className={styles.back_span}>返回我的主页 <RightOutlined /></span></Link>
              </div>
              <div style={{marginTop: 30}}>
                <Row>
                  <Col span={20} offset={4}>
                    <Form
                      autoComplete="off"
                      wrapperCol={{span: 15}}
                      labelCol={{span: 6}}
                      form={form}
                    >
                      <Form.Item
                        label="用户名"
                        name="username"
                        rules={[{required: true, message: '请输入用户名！'}]}>
                        <Input placeholder="请输入用户名" maxLength={20} onChange={(e) => handleSpaces(e, 'username')} />
                      </Form.Item>
                      <Form.Item
                        label="手机号"
                        name="iphone"
                        rules={[{required: true, message: '请输入手机号！'}]}
                      >
                        <Input placeholder="请输入手机号" maxLength={11} />
                      </Form.Item>
                      <Form.Item
                        label="性别"
                        name="gender"
                        rules={[{required: true, message: '请输入性别！'}]}>
                        <Select placeholder="请选择性别">
                          <Option value={0}>女</Option>
                          <Option value={1}>男</Option>
                        </Select>
                      </Form.Item>
                      <Form.Item
                        label="邮箱"
                        name="email"
                        rules={[{required: true, message: '请输入用户名！'}]}>
                        <Input placeholder="请输入邮箱" onChange={(e) => handleSpaces(e, 'email')} />
                      </Form.Item>
                      <Form.Item
                        label="职业"
                        name="job"
                      >
                        <Input placeholder="请输入职业" onChange={(e) => handleSpaces(e, 'job')} />
                      </Form.Item>
                      <Form.Item
                        label="地址"
                        name="address"
                        rules={[{required: true, message: '请选择地址!'}]}
                      >
                        <SelectCity address={address} setAddress={setAddress} />
                      </Form.Item>
                        
                      <Form.Item
                        label="详细地址"
                        name="details_address"
                      >
                        <TextArea
                          placeholder="请输入详细地址"
                          autoSize={{ minRows: 3, maxRows: 5 }}
                          maxLength={50}
                          showCount
                        />
                      </Form.Item>
                      <Form.Item
                        label="头像" name="avatarFile"
                        trigger="setFileList" validateTrigger="setFileList"
                        valuePropName="fileList" 
                        rules={[{required: true, message: '请上传头像'}]}
                      >
                        <UploadFile fileList={avatarFile} setFileList={setAvatarFile} fileType="image" mode="oss" maxCount={1} plural={false} tipsContent="图片大小：180*180，建议3M以内"></UploadFile>
                      </Form.Item>
                      <Form.Item
                        label="封面" name="coverFile"
                        trigger="setFileList" validateTrigger="setFileList"
                        valuePropName="fileList" 
                      >
                        <UploadFile fileList={coverFile} maxCount={1} plural={false} setFileList={setCoverFile} fileType="image" mode="oss" tipsContent="建议尺寸：750*480px，建议3M以内"></UploadFile>
                      </Form.Item>
                      <Form.Item
                        wrapperCol={{
                          offset: 19,
                          span: 15,
                        }}
                      >
                        <Button type="primary" onClick={submitForm}>提 交</Button>
                      </Form.Item>
                    </Form>
                  </Col>
                </Row>
              </div>
            </div>
          </Col>
        </Row>
      </Spin>
    </div>
  )
}

export default  UpdateInfo